package com.lp.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局网关 filter
 */
@Configuration
public class HandlerGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 类似 javaweb doFilter
     * @param exchange 交换 request response，封装了 request response
     * @param chain 决定是否继续向后执行
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取封装 HttpRequest 后的对象
        ServerHttpRequest request = exchange.getRequest();
        System.out.println("-------请求到来，经过全局 Filter 处理-------");
        //对请求做处理......
        Mono<Void> filter = chain.filter(exchange);//放行 filter 向后执行：也就意味接下来进入到具体的微服务中(例如 user 微服务)
        //对响应做处理......
        System.out.println("-------响应回来，经过全局 Filter 处理-------");
        //获取封装 HttpResponse 后的对象
        ServerHttpResponse response = exchange.getResponse();
        System.out.println(response);
        return filter;
    }

    /**
     * order 排序
     * @return 返回一个 int 数字，用来指定 filter 执行顺序，默认按照自然数由小到大顺序排序(越小越先执行)
     *  -1 特殊，表示在所有 filter 执行之前执行
     */
    @Override
    public int getOrder() {
        return -1;
    }

}
